/**
 * Copyright (C), 2020, JieYi Software System Co., Ltd.
 * All rights reserved.
 * FileName:       TableController.java
 *
 * @Description:
 * @author: feiwe
 * Modification History:
 * Date         Author        Version        Discription
 * -------------------------------------------------------
 * 2020/11/16      feiwe                         add
 */


package com.fengwei.controller;

import cn.hutool.system.SystemUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fengwei.form.MapForObject.MapForObject;
import com.fengwei.form.MdmsDatabase;
import com.fengwei.form.MdmsUser;
import com.fengwei.requestdata.table.TableDdlData;
import com.fengwei.requestdata.table.TableExportDataData;
import com.fengwei.requestdata.table.TablePagingListData;
import com.fengwei.service.ConsoleCommonService;
import com.fengwei.service.TableService;
import com.fengwei.util.PltResult;
import com.fengwei.util.ResponseUtil;
import com.fengwei.verify.Verify;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

@Controller
public class TableController {
    private final static Logger logger = LoggerFactory.getLogger(TableController.class);

    @Autowired
    private ConsoleCommonService consoleCommonService;

    @Autowired
    private TableService tableService;

    @GetMapping(value = "/table/loadPage")
    public String loadPage(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        MdmsDatabase currentDatabase = (MdmsDatabase) session.getAttribute("currentDatabaseId");
        String databaseRandomStr = (String) session.getAttribute(currentDatabase.getId() + "");
        String table = request.getParameter("table");
        logger.debug("table:" + table);
        model.addAttribute("table", table);
        model.addAttribute("databaseRandomStr", databaseRandomStr);
        return "table";
    }

    /**
     * 打开表的直接查询
     */
    @PostMapping(path = "/table/pagingList")
    @ResponseBody
    @PreAuthorize("hasAnyRole('DBA','USER')")
    public Map<String, Object> pagingList(@RequestBody Map<String, Object> jsonObject, HttpServletRequest request) throws Exception {
        consoleCommonService.checkAndGetUser(request);
        TablePagingListData tablePagingListData = new ObjectMapper().convertValue(new MapForObject(jsonObject).getData(), new TypeReference<TablePagingListData>() {
        });

        // 校验传入参数
        Verify.verifyData(tablePagingListData);
        // 正式处理业务
        Map<String, Object> data = tableService.pagingList(tablePagingListData, request);

        return ResponseUtil.toJson(PltResult.RESULT_0000, data);
    }

    /**
     * 表的ddl
     */
    @PostMapping(path = "/table/ddl")
    @ResponseBody
    @PreAuthorize("hasAnyRole('DBA','USER')")
    public Map<String, Object> ddl(@RequestBody Map<String, Object> jsonObject, HttpServletRequest request) throws Exception {
        MdmsUser mdmsUser = consoleCommonService.checkAndGetUser(request);
        TableDdlData tableDdlData = new ObjectMapper().convertValue(new MapForObject(jsonObject).getData(), new TypeReference<>() {
        });

        // 校验传入参数
        Verify.verifyData(tableDdlData);
        // 正式处理业务
        Map<String, Object> data = tableService.ddl(tableDdlData, request, mdmsUser);

        return ResponseUtil.toJson(PltResult.RESULT_0000, data);
    }

    /**
     * 导出数据
     */
    @PostMapping(path = "/table/exportData")
    @ResponseBody
    @PreAuthorize("hasAnyRole('DBA','USER')")
    public Map<String, Object> exportData(@RequestBody Map<String, Object> jsonObject, HttpServletRequest request) throws Exception {
        consoleCommonService.checkAndGetUser(request);
        TableExportDataData tableExportDataData = new ObjectMapper().convertValue(new MapForObject(jsonObject).getData(),
                new TypeReference<>() {
                });

        // 校验传入参数
        Verify.verifyData(tableExportDataData);
        // 正式处理业务
        Map<String, Object> data = tableService.exportData(tableExportDataData, request);

        return ResponseUtil.toJson(PltResult.RESULT_0000, data);
    }

    /**
     * 获取导出的数据
     */
    @GetMapping(path = "/table/downloadExportData")
    @PreAuthorize("hasAnyRole('DBA','USER')")
    public String downloadExportData(HttpServletRequest request, HttpServletResponse response) throws Exception {
        consoleCommonService.checkAndGetUser(request);

        String excelName = request.getParameter("excelName");

        cn.hutool.system.UserInfo userInfo = SystemUtil.getUserInfo();
        InputStream in = new FileInputStream(userInfo.getHomeDir() + File.separator + "exportData" + File.separator + excelName);

        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setHeader("Content-disposition", "attachment;filename="
                + excelName);

        OutputStream os = response.getOutputStream();
        byte[] b = new byte[1024];
        int size = 0;
        while ((size = in.read(b, 0, b.length)) > 0) {
            os.write(b, 0, size);
        }
        try {
            os.flush();
            os.close();
            in.close();
        } catch (Exception e) {

        } finally {
            File file = new File(userInfo.getHomeDir() + File.separator + "exportData" + File.separator + excelName);
            if (file.exists()) {
                file.delete();
            }
        }

        return null;
    }
}
